package com.ruoyi.cart.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.cart.constants.CartConstants;
import com.ruoyi.cart.constants.RedisConstants;
import com.ruoyi.cart.domain.CartSkuVO;
import com.ruoyi.cart.domain.CartVO;
import com.ruoyi.cart.domain.PmsCart;
import com.ruoyi.cart.mapper.PmsCartMapper;
import com.ruoyi.cart.service.IPmsCartService;
import com.ruoyi.cart.utils.CartUtils;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.coupon.domain.PmsCoupon;
import com.ruoyi.coupon.remote.IPmsCouponRemoteService;
import com.ruoyi.product.domain.Merchant;
import com.ruoyi.product.domain.PmsSkuInfo;
import com.ruoyi.product.remote.IPmsSkuInfoRemoteService;
import com.ruoyi.system.common.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车Service业务层处理
 *
 * @author jorker
 * @date 2024-12-27
 */
@Service
public class PmsCartServiceImpl implements IPmsCartService
{
    @Autowired
    private PmsCartMapper pmsCartMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IPmsSkuInfoRemoteService pmsSkuInfoRemoteService;
    @Autowired
    private IPmsCouponRemoteService pmsCouponRemoteService;

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public PmsCart selectPmsCartById(Long id)
    {
        return pmsCartMapper.selectPmsCartById(id);
    }

    /**
     * 查询购物车列表
     * @return 购物车
     */
    @Override
    public List<CartVO> selectPmsCartList()
    {

        return pmsCartMapper.selectCartVO(SecurityUtils.getLoginUser().getUserid());
    }

    /**
     * 新增购物车
     *
     * @param pmsCart 购物车
     * @return 结果
     */
    @Override
    public int insertPmsCart(PmsCart pmsCart)
    {
        return pmsCartMapper.insertPmsCart(pmsCart);
    }

    /**
     * 修改购物车
     *
     * @param pmsCart 购物车
     * @return 结果
     */
    @Override
    public int updatePmsCart(PmsCart pmsCart)
    {
        return pmsCartMapper.updatePmsCart(pmsCart);
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deletePmsCartByIds(Long[] ids)
    {
        return pmsCartMapper.deletePmsCartByIds(ids);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deletePmsCartById(Long id)
    {
        return pmsCartMapper.deletePmsCartById(id);
    }

    @Override
    public PmsCart selectBySkuId(Long skuId) {

        return pmsCartMapper.selectBySkuId(skuId);
    }


    @Override
    public List<CartVO> showCart() {
        String userCart = RedisConstants.USER_CART+ SecurityUtils.getLoginUser().getUserid();
        Map<String, Object> cacheMap = redisService.getCacheMap(userCart);
        List<CartSkuVO> list = JSONObject.parseObject(JSONObject.toJSONString(cacheMap.values()),
                new TypeReference<List<CartSkuVO>>() {});
        return CartUtils.cartSkuVOS2CartVOS(list);
    }

    @Override
    public void updateSkuCount(Long skuId, Long count) {
        String userCart = RedisConstants.USER_CART+SecurityUtils.getLoginUser().getUserid();
        CartSkuVO cartSkuVO = getRedisSkuBySkuId(userCart, skuId);
        //校对数量
        if (count > CartConstants.MAX_COUNT){
            count=200L;
        }
        cartSkuVO.setCount(count);
        cartSkuVO.setChecked(true);
        redisService.setCacheMapValue(userCart, skuId.toString(),cartSkuVO);
    }

    @Override
    public void removeSkuFromCart(Long skuId) {
        String userCart = RedisConstants.USER_CART+SecurityUtils.getLoginUser().getUserid();
        //删除sku
        redisService.deleteCacheMapValue(userCart,skuId.toString());
        //判断购物车是否为空
        Map<String, Object> cacheMap = redisService.getCacheMap(userCart);
        //为空删除购物车
        if (cacheMap.isEmpty()){
            redisService.deleteObject(userCart);
        }
    }

    @Override
    public void addSkuInCart(Long skuId, Long count) {
        String userCart = RedisConstants.USER_CART+SecurityUtils.getLoginUser().getUserid();
        //Redis中没有购物车
        if (!redisService.hasKey(userCart)) {
            //创建该用户的购物车
            redisService.setCacheMap(userCart,null);
        }
        //有购物车，查看购物车是否有商品
        Object cacheMapValue = redisService.getCacheMapValue(userCart, skuId.toString());
        String s = JSONObject.toJSONString(cacheMapValue);
        CartSkuVO cartSkuVO = JSONObject.parseObject(s, CartSkuVO.class);

        //没有商品
        if (cartSkuVO == null){
            cartSkuVO = getCartSku(skuId);
        }

        //将商品放入购物车中
        cartSkuVO.setCount(cartSkuVO.getCount()+count);

        redisService.setCacheMapValue(userCart, skuId.toString(),cartSkuVO);
    }

    @Override
    public PmsCart selectByMerchantIdAndUser(Long merchantId, Long userId) {
        return pmsCartMapper.selectByMerchantIdAndUser(merchantId,userId);
    }

    protected CartSkuVO getRedisSkuBySkuId(String userCart,Long skuId){

        //获取购物车
        Object cacheMapValue = redisService.getCacheMapValue(userCart, skuId.toString());
        //判断是否有商品
        if (cacheMapValue == null){
            throw new RuntimeException("错误操作,购物车中没有此商品");
        }
        //获取购物车商品明细
        return JSONObject.parseObject(JSONObject.toJSONString(cacheMapValue),
                new TypeReference<CartSkuVO>() {
                });
    }

    @Override
    public void updateCheck(Long skuId, Boolean checked) {
        String userCart = RedisConstants.USER_CART+SecurityUtils.getLoginUser().getUserid();
        CartSkuVO cartSkuVO = getRedisSkuBySkuId(userCart,skuId);
        cartSkuVO.setChecked(checked);
        redisService.setCacheMapValue(userCart, skuId.toString(),cartSkuVO);
    }

    @Override
    public List<CartVO> listCheck() {
        String userCart = RedisConstants.USER_CART+ SecurityUtils.getLoginUser().getUserid();
        Map<String, Object> cacheMap = redisService.getCacheMap(userCart);
        List<CartSkuVO> list = JSONObject.parseObject(JSONObject.toJSONString(cacheMap.values()),
                new TypeReference<List<CartSkuVO>>() {});

        List<CartSkuVO> collect = list.stream().filter(CartSkuVO::getChecked).collect(Collectors.toList());
        return CartUtils.cartSkuVOS2CartVOS(collect);
    }

    @Override
    public void removePayed(Long... skuIds) {
        for (Long skuId : skuIds) {
            this.removeSkuFromCart(skuId);
        }
    }

    /**
     * 通过skuId构建购物车明细
     * @param skuId skuId
     * @return 购物车明细
     */
    public CartSkuVO getCartSku(Long skuId){
        //商品信息
        CartSkuVO cartSkuVO = new CartSkuVO();
        //拷贝基本属性
        PmsSkuInfo pmsSkuInfo = pmsSkuInfoRemoteService.getInfo(skuId).getData();
        BeanUtils.copyProperties(pmsSkuInfo,cartSkuVO);
        //查询属性
        List<String> attrs = pmsSkuInfoRemoteService.getSaleAttrBySkuId(skuId).getData();
        cartSkuVO.setAttrs(attrs);
        //商家信息
        Merchant merchant = pmsSkuInfoRemoteService.getMerchantBySkuId(skuId).getData();
        BeanUtils.copyProperties(merchant,cartSkuVO);
        //数量和选择
        cartSkuVO.setCount(0L);
        cartSkuVO.setChecked(false);

        Result<List<PmsCoupon>> listResult = pmsCouponRemoteService.selectCouponByCart(skuId);
        List<PmsCoupon> list = listResult.getData();
        if (!CollectionUtils.isEmpty(list)) {
            cartSkuVO.setPmsCoupons(list);
        }
        return cartSkuVO;
    }
}
